//导入数据库
const db=require('../db/index')

exports.supplierall= (req,res)=>{
    const sql='select * from supplier'
    db.query(sql,(err,results)=>{
        if(err){ return res.cc(err)}
        res.json(results)
    })
}
exports.supplierfind= (req,res)=>{
    var sql=` select * from supplier ` 
    var info=req.body
    var type=info.selecttype
    if(info.inputtext.length!=0){
        var name=info.inputtext
        sql+=` where `
        if(type=='sup_name')
        {
            sql+=` sup_name like '%${name}%' `
        }else if(type=='sup_address')
        {
            sql+=` sup_address like '%${name}%' `
        }
    }
    console.log(sql)
    db.query(sql,(err,results)=>{
        if(err){ return res.cc(err)}
        res.json(results)
    })
}


exports.deletesupplier= (req,res)=>{
    const supplierinfo=req.body
    const sql='delete from supplier where sup_id=?'
    db.query(sql,supplierinfo.id,(err,results)=>{
        if(err) return res.cc(err)
        if(results.affectedRows!=1)return res.cc('failed to delete')
        res.cc('delete successfully',0)
    })
}

exports.insertsupplier= (req,res)=>{
    const supplierinfo=req.body
    const sql='select * from supplier where sup_name=?'
    db.query(sql,supplierinfo.username,(err,results)=>{
        if(err) return res.cc(err)
        if(results.length==1) res.cc('sort name is exist,please change new and try again')
        const sql='insert into supplier set  ?'
        db.query(sql,{sup_name:supplierinfo.username,sup_address:supplierinfo.address,sup_tel:supplierinfo.tel},(err,results)=>{
        if(err) return res.cc(err)
        if(results.affectedRows!=1)return res.cc('failed to insert')
        res.cc('insert successfully',0)
    })
    })

    
}
exports.updatesupplier= (req,res)=>{
    const supplierinfo=req.body
    const sql='update supplier set ? where sup_id=?'
    db.query(sql,[{sup_name:supplierinfo.username,sup_address:supplierinfo.address,sup_tel:supplierinfo.tel},supplierinfo.id],(err,results)=>{
        if(err) return res.cc(err)
        if(results.affectedRows!=1)return res.cc('failed to update')
        res.cc('update successfully',0)
    })
}

